package com.mind.customer.controller;

import com.mind.customer.api.oss.OSSUtils;
import com.mind.customer.config.FileConfig;
import org.springframework.core.io.FileSystemResource;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import jakarta.annotation.Resource;
import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;

@RestController
@RequestMapping("file")
public class FileController {
    @Resource
    private FileConfig fileConfig;

    @Resource
    private OSSUtils ossUtils;
    @GetMapping(value="{bucketName}/{fileName}", produces = MediaType.IMAGE_JPEG_VALUE)
    public ResponseEntity<org.springframework.core.io.Resource> download(@PathVariable("bucketName") String bucketName, @PathVariable("fileName") String fileName) throws IOException {
        Path path = Paths.get(fileConfig.getBasePath(), fileName);
        File file = new File(path.getParent().toString());
        if (!file.exists()) {
            file.mkdirs();
        }
        File imageFile = new File(path.toString());
        if(!imageFile.exists()) {
            ossUtils.download(fileName, path.toString());
        }
        String contentType = Files.probeContentType(imageFile.toPath());

        // 如果无法探测到MIME类型，可以设置为默认类型，例如application/octet-stream
        if (contentType == null || contentType.isEmpty()) {
            contentType = "application/octet-stream";
        }
        if (imageFile.exists() && !imageFile.isDirectory()) {
            // 使用 Resource 来包装文件
            return ResponseEntity.ok()
                    .contentType(MediaType.parseMediaType(contentType))
                    .body(new FileSystemResource(imageFile));
        } else {
            return ResponseEntity.notFound().build();
        }
    }
}
